package kz.kstu.shop.business.server.impl;

import kz.kstu.shop.business.entity.Synchronizable;
import kz.kstu.shop.business.server.api.SyncService;
import org.apache.log4j.Logger;

import javax.persistence.Query;
import java.util.List;

/**
 * @author Filipp_Stankevich
 *         created: 8/9/11 5:53 PM
 */
public class SyncServiceImpl extends AbstractService implements SyncService {

    private final static Logger LOGGER = Logger.getLogger(SyncServiceImpl.class);

    @Override
    public <T extends Synchronizable> List<Synchronizable> findForSync(Class<T> classForSync, Long changeDate) {
        LOGGER.info("find entities for sync... start");
        String className = classForSync.getSimpleName();
        Query query = getEntityManager().createQuery("select c from " + className + " c where c.changeDate > :date");
        query.setParameter("date", changeDate);
        List<Synchronizable> entities = (List<Synchronizable>) query.getResultList();
        LOGGER.info("find entities for sync... ok. Size = " + entities.size());
        return entities;
    }

    public void saveSycnhronazable(List<Synchronizable> entities) {
        for (Synchronizable entity : entities) {
            Synchronizable oldEntity = null;
            Long id = entity.getId();
            if (id != null) {
                oldEntity = getEntityManager().find(entity.getClass(), id);
            }
            if (oldEntity != null) {
                getEntityManager().merge(entity);
            } else {
                entity.setId(null);
                getEntityManager().persist(entity);
            }
        }
    }
}
